import jwt from 'jsonwebtoken';
import type { Response, NextFunction } from 'express';
import type { AuthenticatedRequest } from '../types/custom';
import { ResponseUtil } from '../utils/response';

export const authMiddleware = (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
  try {
    // const token = req.header('Authorization')?.replace('Bearer ', '');
    const token = req.header('token');
    
    if (!token) {
      return ResponseUtil.error(res, '未提供认证令牌');
    }

    const decoded = jwt.verify(token, process.env.JWT_SECRET || 'your-secret-key') as { userId: number; account: string };
    req.user = decoded;
    next();
  } catch (error) {
    ResponseUtil.error(res, '无效的认证令牌');
  }
}; 